#include "drv_timer.h"
#include <stdio.h>

#define SOFT_TIMER_MAX_CNT	32

static Timer_t timer_array[SOFT_TIMER_MAX_CNT] = {0};
static uint8_t createdTimerCnt = 0;//已经创建的定时器数量

Timer_t *timer_create(Timer_Excu_Func func,uint32_t period_ms){
	if(createdTimerCnt < SOFT_TIMER_MAX_CNT){
		timer_array[createdTimerCnt].func = func;
		timer_array[createdTimerCnt].period_ms = period_ms;
		timer_array[createdTimerCnt].active_flag = 0;//创建后，先不执行
		timer_array[createdTimerCnt].cnt_ms = 0;
		createdTimerCnt ++;
		return &timer_array[createdTimerCnt - 1];
	}
	printf("create timer failed!\n");
	return NULL;
}

void timer_reset(Timer_t *timer){
	timer->cnt_ms = 0;
}

void timer_start(Timer_t *timer){
	timer->active_flag = 1;
}

void timer_stop(Timer_t *timer){
	timer->active_flag = 0;
}

void timer_start_all(void){
	TIMER0_Cmd(M4_TMR02,Tim0_ChannelA,Enable);
}

void timer_stop_all(void){
	TIMER0_Cmd(M4_TMR02,Tim0_ChannelA,Disable);
}

void refresh_timing_task(void){
	for(uint8_t i = 0;i<createdTimerCnt;i++){
		if(timer_array[i].excute_flag == 1){
			uint32_t temp_1ms = timer_array[i].cnt_ms;
			timer_array[i].cnt_ms = 0;
			timer_array[i].func((void *)&temp_1ms);
			
			timer_array[i].excute_flag = 0;
		}
	}
}

void time0_callback(void){
	for(uint8_t i = 0;i<createdTimerCnt;i++){
		if(timer_array[i].active_flag == 1){//如果定时器执行标志时允许执行
			timer_array[i].cnt_ms ++;
			if(timer_array[i].excute_flag == 0){
				if(timer_array[i].cnt_ms >= timer_array[i].period_ms){
					timer_array[i].excute_flag = 1;
				}
			}
		}else{
			timer_array[i].cnt_ms = 0;
			timer_array[i].excute_flag = 0;
		}
	}
}
